import axios from "axios";
import {ElMessage, ElNotification} from 'element-plus'
import qs from "qs"
const TOKEN_INVALID = 'token 认证失败，请重新登陆！'
const ENTWORK_ERROR = '网络请求异常，请稍后重试！'
//创建axios实例对象，添加全局配置
const service = axios.create({
    baseURL: "http://129.226.145.230",
    timeout: 8000,
    headers: {
        contentType : 'application/json;charset=UTF-8',
    }
})

//请求拦截
service.interceptors.request.use((req) => {
    req.data = qs.stringify(req.data)
    return req
})

service.interceptors.response.use((res) => {
    const {data, status, statusText} = res
    if (status === 200) {
        if (data.code === 500) {
            ElNotification({
                message: data.msg,
                type: 'error',
                showClose: false,
                duration: 2000
            })
            return;
        }
        return data;
    } else if (status === 40001) {
        ElMessage.error(TOKEN_INVALID)
        setTimeout(() => {
        }, 1500)
        return Promise.reject(TOKEN_INVALID)
    } else {
        ElMessage.error(statusText || ENTWORK_ERROR)
        return Promise.reject(statusText || ENTWORK_ERROR)
    }
})

/**
 * 请求核心函数
 * @param {*} options 请求配置
 * @returns
 */

const request = (options) => {
    options.method = options.method || 'get'
    if (options.method.toLowerCase() === 'get') {
        options.params = options.data
    }
    return service(options)

}

['get', 'post', 'put', 'delete', 'patch'].forEach((item) => {
    request[item] = (url, data, options) => {
        return request({
            url,
            data,
            method: item,
            ...options
        })
    }
})

export default request
